import fitz
from PIL import Image, ImageDraw,ImageChops
import cv2
import numpy as np

def extract_text(pdf_path):
    text_list = []
    
    pdf = fitz.open(pdf_path)
    for page in pdf:  # iterate through the pages
        text_list.append(page.get_text())
    pdf.close()
    return text_list

def extract_images(pdf_path):
    image_list = []
    
    pdf = fitz.open(pdf_path)
    for page in pdf:  # iterate through the pages
        img_list = page.get_images(full=True)
        
        for img in img_list:
            base_image = fitz.Pixmap(pdf, img[0])
            image_list.append(Image.frombytes("RGB", [base_image.width, base_image.height], base_image.samples))
            #image_list.append(base_image)
    pdf.close()
    return image_list

def compare_text(text1, text2):
    if text1 != text2:
        print("Text content is different!")
        # Optionally, you can output the differences using difflib or similar library

def compare_images(image1, image2):

    # 加载图片
    #img1 = cv2.imread(image1)
    #img2 = cv2.imread(image2)
     # 将PIL Image转换为OpenCV图像格式
    img1 = np.array(image1)
    img2 = np.array(image2)

    # 转为灰度图像
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    # 计算绝对差值
    diff = cv2.absdiff(gray1, gray2)

    # 二值化差异图，便于观察和标注
    _, thresh = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)

    # 找到轮廓进行标注
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        if cv2.contourArea(contour) > 0:  # 忽略小区域噪声
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(img1, (x, y), (x+w, y+h), (0, 0, 255), 2)  # 用红色矩形标注差异
    #print(contours)
    cv2.imshow('Difference', img1)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Main comparison function
def compare_pdfs(pdf1_path, pdf2_path):
    text1 = extract_text(pdf1_path)
    text2 = extract_text(pdf2_path)
    compare_text(text1, text2)

    images1 = extract_images(pdf1_path)
    images2 = extract_images(pdf2_path)

    print("image_list-lenth:",len(images1))
    print("image_list-lenth:",len(images2))
    
    if len(images1) != len(images2):
        print("The number of images is different!")
    else:
        for i in range(len(images1)):
            pass
            compare_images(images1[i], images2[i])

# Example usage
compare_pdfs('0708.pdf', '07082.pdf')



# 调用函数
#compare_pdf_text('0708.pdf', '07082.pdf')
#compare_pdf_images('0708.pdf', '07082.pdf',5)